/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.liquidByte.trafficMustang.server.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.liquidByte.trafficMustang.server.repository.ReadableRepository;

/**
 *
 * @author Alexandre
 */
public abstract class ReadableDAO<T> implements ReadableRepository<T> {
    
    @PersistenceContext
    private EntityManager em;
    private Class<T> classType;
    
    ReadableDAO(Class<T> classType) {
        this.classType = classType;
    }

    EntityManager getEntityManager() {
        return this.em;
    }

    Class<T> getClassType() {
        return classType;
    }
    
    public List<T> getAll() {
        CriteriaBuilder builder = this.em.getCriteriaBuilder();
        CriteriaQuery<T> query = builder.createQuery(this.classType);
        Root<T> root = query.from(this.classType);
        query.select(root);
        return this.em.createQuery(query).getResultList();
    }

    public T getById(Object id) {
        return this.em.find(this.classType, id);
    }
    
    public void flush() {
        this.em.flush();
    }
}
